import {createSlice} from "@reduxjs/toolkit";
import {
    getProjectCountAPI,
    getProjectCountByNameAPI,
    getProjectInfoAPI,
    getProjectListAPI,
    getProjectListByNameAPI
} from "@/apis/project.jsx";


const projectStore=createSlice({
    name:'project',
    initialState:{
        projectInfo_init:{},
        projectList_init:[],
        projectCount_init:0,
        projectCur_init:1,
        projectPageSize_init:11,
        projectDriveListChange_init:0
    },
    reducers:{
        getProjectInfo(state,action){
            state.projectInfo_init=action.payload
        },
        getProjectList(state,action){
            state.projectList_init=action.payload
        },
        getProjectCount(state,action){
            state.projectCount_init=action.payload
        },
        setProjectCur(state,action){
            state.projectCur_init=action.payload;
        },
        setProjectPageSize(state,action){
            state.projectPageSize_init=action.payload;
        },
        setProjectDriveListChange(state,action){
            state.projectDriveListChange_init=action.payload;
        }
    }
})
const {
    setProjectDriveListChange,
    getProjectInfo,
    getProjectList,
    getProjectCount,
    setProjectCur,
    setProjectPageSize}=projectStore.actions;

// 异步请求函数
// 分页获取所有数据
 const fetchGetProjectList=(cur,pageSize)=>{
    return async (dispatch)=>{
        const res=await getProjectListAPI(cur,pageSize);
        dispatch(getProjectList(res.data))
    }
}
const fetchGetProjectInfo=(id)=>{
    return async (dispatch)=>{
        const res=await getProjectInfoAPI(id);
        dispatch(getProjectInfo(res.data))
    }
}
const fetchGetProjectCount=()=>{
    return async (dispatch)=>{
        const res=await getProjectCountAPI();
        dispatch(getProjectCount(res.data))
    }
}

// 根据项目名称查询项目
const fetchGetProjectListByName=(name,cur,pageSize)=>{
    return async (dispatch)=>{
        const res=await getProjectListByNameAPI(name,cur,pageSize);
        console.log(res.data);
        dispatch(getProjectList(res.data));

    }
}
const fetchGetProjectCountByName=(name)=>{
    return async (dispatch)=>{
        const res=await getProjectCountByNameAPI(name);
        console.log(res.data);
        dispatch(getProjectCount(res.data))
    }
}

const projectReducer=projectStore.reducer;
export {
    fetchGetProjectList,
    fetchGetProjectInfo,
    fetchGetProjectCount,
    fetchGetProjectListByName,
    fetchGetProjectCountByName,
    setProjectCur,
    setProjectPageSize,
    setProjectDriveListChange
}

export default projectReducer;